package de.akabahn.ebd.fst.control;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

import org.apache.log4j.Logger;

/**
 * Class that manages the connection requests from the clients to the
 * Fahrsteuerung-Control application.
 * 
 * @author Peter Eimann
 * @since 1.0
 * @version 1.0
 * @see ClientCommunicationHandler
 */
public class ClientConnectionHandler implements Runnable {

	private final static Logger LOG = Logger.getLogger(ClientConnectionHandler.class);

	private FahrSteuerungControl control;

	/**
	 * Initialize this instance
	 * 
	 * @param control
	 *            The control instance
	 */
	public ClientConnectionHandler(FahrSteuerungControl control) {
		this.control = control;
	}

	/**
	 * The loop to handle the connection requests from the clients:
	 * <ol>
	 * <li>Listen for incoming connections on the server socket</li>
	 * <li>Create a new <code>ClientCommunicationHandler</code> instance for
	 * each incoming request</li>
	 * <li>Create a new thread that handles the client connection (using a
	 * cached thread pool)</li>
	 * </ol>
	 * These steps are repeated until the server socket is closed.<br>
	 * 
	 * @see ClientCommunicationHandler#run()
	 */
	public void run() {
		ServerSocket serverSocket = control.getServerSocket();
		ExecutorService threadPool = control.getThreadPool();

		try {
			while (true) {
				LOG.info(control.getServerSocket().getLocalPort() + " | Waiting for incoming connection...");
				Socket client = serverSocket.accept();

				LOG.info(control.getServerSocket().getLocalPort() + " | Starting ClientCommunicationHandler");
				threadPool.execute(new ClientCommunicationHandler(client, control));
			}
		} catch (IOException e) {
			LOG.error("Exception", e);
		} finally {
			System.exit(0);
		}
	}
}
